let tableIns;
let tree;
let element;
let form;
let transfer;
let dropdown;
//
let downSourceWeb = []
let downSourceCategory = []
layui.use(['element', 'form', 'transfer', 'table', 'layer', 'laydate', 'tree', 'util', 'dropdown'], function () {
    // 声明
    element = layui.element;
    form = layui.form;
    transfer = layui.transfer;
    tree = layui.tree;
    dropdown = layui.dropdown;
    let table = layui.table;
    let auth_token = localStorage.getItem('auth_token');
    let headers = {
        // Basic bearer
        'Authorization': auth_token
        //'Authorization':'Basic '+auth_token
    }
    // 隐藏编辑及诶按
    tableIns = table.render({
        elem: '#sourceTable'
        , url: '/book/source/v1/queryBookSourcePage'
        , method: 'POST'
        // JWT
        , headers: headers
        , where: {
            sourceTxt: ''
        }
        , parseData: function (res) { //res 即为原始返回的数据
            let result = {};
            if (res.code === '00000') {
                result = {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                }
            } else {
                result = {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": 0, //解析数据长度
                    "data": {} //解析数据列表
                }
            }
            return result;
        }
        , done: function (res, curr, count) {
        }
        , page: true
        , limit: 15
        , limits: [15, 30, 45, 60]
        //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , cellMinWidth: 80
        //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
        , toolbar: '#toolbarSource' // 开启头部工具栏，并为其绑定左侧模板
        // 自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
        , defaultToolbar: ['filter', 'exports']
        , title: '车辆数据表'
        // width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'sourceId', title: 'ID', sort: true, hide: true}
            , {field: 'sourceTitle', title: '网站标题'}
            , {field: 'sourceWeb', title: '网站源', hide: true}
            , {field: 'sourceWebName', title: '网站源'}
            , {field: 'sourceCategory', title: '网站分类', hide: true}
            , {field: 'sourceCategoryName', title: '网站分类'}
            , {field: 'sourceUrl', title: '网站地址'}
            , {field: 'sourceCrawlPath', title: '网站分类地址'}
            , {
                field: 'sourceState', title: '是否可用', templet: function (row) {
                    let state = '<div className="layui-input-block">';
                    if (row.sourceState) {
                        state += '<input type="checkbox" lay-skin="switch" checked lay-text="ON|OFF" disabled="disabled">';
                    } else {
                        state += '<input type="checkbox" lay-skin="switch" lay-text="ON|OFF" disabled="disabled">';
                    }
                    state = state + '</div>';
                    return state;
                }
            }
            , {
                field: 'sourceDownloadType', title: '下载方式', templet: function (row) {
                    //下载类型(1-网址下载;2-解析章节下载)
                    if (row.sourceDownloadType == 1) {
                        return '网址下载';
                    } else if (row.sourceDownloadType == 2) {
                        return '章节下载';
                    }
                }
            }
            , {field: 'lastUpdateTime', title: '最后更新时间'}
            , {fixed: 'right', title: '操作', toolbar: '#barSource', width: 200}
        ]]
    });

    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        switch (obj.event) {
            case 'syncData':
                $.DGet("/book/source/v1/crawlingAllBook", {}, headers, function (data) {
                    console.log("crawlingAllBook success");
                    layer.msg("同步已触发..", {icon: 1, time: 2000, offset: 'rb'});
                });
                break;
            case 'addData':
                sourceEditSub(headers, 'add', null)
                break;
            case 'query':
                let sourceTxt = $("#sourceTxt").val();
                let query = {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , done: function (res, curr, count) {
                        //完成后重置where，解决下一次请求携带旧数据
                        // this.where = {};
                    }
                };
                if (!sourceTxt) {
                    sourceTxt = "";
                }
                //设定异步数据接口的额外参数
                query.where = {sourceTxt: sourceTxt};
                tableIns.reload(query);
                $("#sourceTxt").val(sourceTxt);
                break;
            case 'reload':
                tableIns.reload();
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        let data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确认删除吗？', function (index) {
                // 向服务端发送删除指令
                $.delete("/book/source/v1/delete?sourceId=" + data.sourceId, {}, headers, function (data) {
                    if (data.code === '00000') {
                        layer.msg('删除成功', {icon: 6});
                    } else {
                        layer.msg(data.msg, {icon: 6});
                    }
                    // 表格刷新
                    tableIns.reload();
                    layer.close(index);
                })
            });
        } else if (obj.event === 'edit') {
            sourceEditSub(headers, 'edit', data)
        } else if (obj.event === 'getBook') {
            if (data.sourceState) {
                getBookSub(headers, data)
            } else {
                layer.alert("网站分类地址不可用", {icon: 5});
            }

        }
    });

});

/**
 * 用户编辑
 */
function sourceEditSub(headers, type, sourceData) {
    // 重置表单
    $("#sourceForm")[0].reset();
    layer.open({
        type: '1',
        content: $('.sourceEditDiv'),
        title: '编辑',
        area: ['850px'],
        btn: ['保存', '取消'],
        closeBtn: '1',
        success: function (layero, index) {
            $.DGet("/common/v1/queryCommonManyCode", {codes: "10002,10003"}, headers, function (data) {
                // 查询所有司机准备渲染下拉菜单
                if (data.code === '00000') {
                    downSourceWeb = data.data[10003];
                    downSourceCategory = data.data[10002];
                    dropdown.render({
                        elem: '#sourceCategory' //也可绑定到 document，从而重置整个右键
                        , style: 'width: 235px' //定义宽度，默认自适应
                        , id: 'id' //定义唯一索引
                        , data: downSourceCategory
                        , click: function (obj) {
                            // 父节点
                            this.elem.val(obj.title);
                            $('#sourceCategoryHidden').val(obj.id);
                        }
                    });
                    dropdown.render({
                        elem: '#sourceWeb' //也可绑定到 document，从而重置整个右键
                        , style: 'width: 235px' //定义宽度，默认自适应
                        , id: 'id' //定义唯一索引
                        , data: downSourceWeb
                        , click: function (obj) {
                            // 父节点
                            this.elem.val(obj.title);
                            $('#sourceWebHidden').val(obj.id);
                        }
                    });
                }
                // 初始化
                if (type === 'edit') {
                    //回显操作表单
                    console.log('sourceData::', sourceData)
                    const checkbox = document.querySelector('input[name="sourceState"]');
                    if (sourceData.sourceState) {
                        checkbox.checked = true; //选中
                    } else {
                        checkbox.checked = false; //不选中
                    }
                    $("#sourceForm").form(sourceData);
                    form.render();
                    // $("input[name='sourceCategory'][value="+sourceData.sourceCategory+"]").prop("checked",true);
                    const sourceCategoryMap = downSourceCategory.reduce((acc, cur) =>{
                        acc.set(cur.id, cur.title);
                        return acc;
                    }, new Map());
                    $('#sourceCategory').val(sourceCategoryMap.get(sourceData.sourceCategory));
                    $('#sourceCategoryHidden').val(sourceData.sourceCategory);
                    const sourceWebMap = downSourceWeb.reduce((acc, cur) =>{
                        acc.set(cur.id, cur.title);
                        return acc;
                    }, new Map());
                    $('#sourceWeb').val(sourceWebMap.get(sourceData.sourceWeb));
                    $('#sourceWebHidden').val(sourceData.sourceWeb);
                }
            });
        },
        btn1: function (index, layero) {
            if (!validateBookSourceCode(layero)) {

            } else {
                //编辑回调
                layer.close(index);
                let carEditLoadIndex = layer.load(2);
                let sourceForm = $("#sourceForm").serializeObject();
                const checkbox = document.querySelector('input[name="sourceState"]');
                if (checkbox.checked) {
                    sourceForm.sourceState = true;
                } else {
                    sourceForm.sourceState = false;
                }
                $.DPost("/book/source/v1/saveOrUpdate", sourceForm, headers, function (data) {
                    if (data.code === '00000') {

                        layer.msg("保存成功", {icon: 1, time: 200, offset: 'rb'}, function () {
                            layer.close(carEditLoadIndex);
                            // 关闭当前页面
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 刷新父页面table(连同查询条件)：
                            // parent.layui.table.reload('userTable');
                            // 表格刷新
                            tableIns.reload();
                        });
                    } else {
                        layer.msg("保存失败", {icon: 1, time: 500, offset: 'rb'}, function () {
                            layer.close(carEditLoadIndex);
                            // 关闭当前页面
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 刷新父页面table(连同查询条件)：
                            // parent.layui.table.reload('userTable');
                            // 表格刷新
                            tableIns.reload();
                        });
                    }

                });
            }
        },
        btn2: function (index, layero) {
            //取消回调
        }
    })
}

function getBookSub(headers, sourceData) {
    $.DGet("/book/source/v1/crawlingCategoryBook", {sourceId: sourceData.sourceId}, headers, function (data) {
        console.log("crawlingCategoryBook success");
        layer.msg("获取已触发..", {icon: 1, time: 2000, offset: 'rb'});
    });
}


/**
 * 表单验证
 */
function validateBookSourceCode(layero) {
    let sourceTitle = $('#sourceTitle').val();
    let sourceUrl = $('#sourceUrl').val();
    let sourceCrawlPath = $('#sourceCrawlPath').val();
    if ($.trim(sourceTitle) == '' || $.trim(sourceTitle).length <= 0) {
        layer.alert("网站标题不能为空", {icon: 5});
        return false;
    } else {
        let msg;
        if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(sourceTitle)) {
            msg = '书籍标题不能有特殊字符';
        }
        if (/(^\_)|(\__)|(\_+$)/.test(sourceTitle)) {
            msg = '书籍标题首尾不能出现下划线\'_\'';
        }
        if (/^\d+\d+\d$/.test(sourceTitle)) {
            msg = '书籍标题不能全为数字';
        }
        if (msg) {
            layer.alert(msg, {icon: 5});
            return false;
        }
    }
    if ($.trim(sourceUrl) == '' || $.trim(sourceUrl).length <= 0) {
        layer.alert("网站地址不能为空", {icon: 5});
        return false;
    } else {
        let msg;
        if (!new RegExp("^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$").test(sourceUrl)) {
            msg = '错误的网站分类地址';
        }
        if (msg) {
            layer.alert(msg, {icon: 5});
            return false;
        }
    }

    if ($.trim(sourceCrawlPath) == '' || $.trim(sourceCrawlPath).length <= 0) {
        layer.alert("网站分类地址不能为空", {icon: 5});
        return false;
    } else {
        let msg;
        if (!new RegExp("^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$").test(sourceCrawlPath)) {
            msg = '错误的网站分类地址';
        }
        if (msg) {
            layer.alert(msg, {icon: 5});
            return false;
        }
    }

    return true;
}



